/**
 *
 * (c) Copyright Ascensio System SIA 2024
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.onlyoffice.integration.configuration;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import java.util.List;

/**
 * 配置Spring Security的安全策略.
 * 包括禁止CSRF保护、基于IP地址的访问控制、表单登录和HTTP基本认证。
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //private final List<String> allowedIps = List.of("10.11.10.69", "172.15.0.4",   "127.0.0.1", "0:0:0:0:0:0:0:1");

    @Value("#{'${allowed.ips}'.split(',')}")
    private List<String> allowedIps;

    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http
                .csrf().disable()//禁用CSRF（跨站请求伪造）
                .authorizeRequests()
                // 允许来自特定IP的请求
                .requestMatchers(request -> {
                            System.out.println("request.getRemoteAddr():" + request.getRemoteAddr());
                            return allowedIps.contains(request.getRemoteAddr());
                        } // 替换为你希望允许的IP
                ).permitAll()
                // 其他请求需要认证
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .httpBasic();
    }
    @Override
    protected void configure(final AuthenticationManagerBuilder auth) throws Exception {

        super.configure(auth);
    }
}
